package com.bw.gmallbi.controller;


import com.bw.gmallbi.bean.*;
import com.bw.gmallbi.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/sugar/api")
public class SugarController {
    @Autowired
    private ProductStatsService productStatsService;
    @Autowired
    private ProvinceStatsService provinceStatsService;
    @Resource
    private VisitorStatsService visitorStatsService;
    @Resource
    private KeywordStatsService keywordStatsService;
    @Autowired
    private ProtalPersonService protalPersonService;


    @RequestMapping("/getgmv")
    public String getGmv(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (0 == date) {
            date = now();
        }
        BigDecimal gmv = productStatsService.getGMV(date);
        return "{" +
                "  \"status\": 0," +
                "  \"msg\": \"\"," +
                "  \"data\": " + gmv + "" +
                "}";
    }

    @RequestMapping("/getGmvByTm")
    public String getGmvByTm(@RequestParam(value = "date", defaultValue = "0") Integer date, @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
        if (0 == date) {
            date = now();
        }
        List<ProductStats> productStats = productStatsService.getGMVByTm(date, limit);

        List<String> tms = new ArrayList<>();
        List<String> series = new ArrayList<>();
        for (ProductStats productStat : productStats) {
            tms.add(productStat.getTm_name());
            series.add(productStat.getOrder_amount().toString());
        }

        String json = "{\"status\": 0,\"data\": " +
                "{\"categories\": [\"" + StringUtils.join(tms, "\",\"") + "\"]," +
                "\"series\": [{\"name\": \"商品品牌\",\"data\": [" + StringUtils.join(series, ",") + "]}]}}";
        return json;
    }


    @RequestMapping("/getGmvByCt")
    public Object getGmvByCt(@RequestParam(value = "date", defaultValue = "0") Integer date, @RequestParam(value = "limit", defaultValue = "5") Integer limit) {

        List<ProductStats> productStats = productStatsService.getGMVByCt(date, limit);

        Map resMap = new HashMap();
        List dataList = new ArrayList();

        for (ProductStats p : productStats) {
            Map dataMap = new HashMap();
            dataMap.put("name", p.getCategory3_name());
            dataMap.put("value", p.getOrder_amount());
            dataList.add(dataMap);
        }
        //[(k,v),(k,v)]
        resMap.put("status", 0);
        resMap.put("msg", "");
        resMap.put("data", dataList);
        return resMap;
    }


    @RequestMapping("/spu")
    public Object getProductStatsBySpu(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        if (date == 0) {
            date = now();
        }

        List<ProductStats> productStatsList = productStatsService.getProductStatsBySPU(date, limit);

        Map resMap = new HashMap();
        Map dataMap = new HashMap();

        List columnList = new ArrayList();
        Map column1 = new HashMap();
        Map column2 = new HashMap();
        Map column3 = new HashMap();
        column1.put("name", "商品名称");
        column1.put("id", "name");
        column2.put("name", "交易额");
        column2.put("id", "amount");
        column3.put("name", "订单数");
        column3.put("id", "ct");
        columnList.add(column1);
        columnList.add(column2);
        columnList.add(column3);

        List rowList = new ArrayList();
        for (ProductStats productStats : productStatsList) {
            Map row = new HashMap();
            row.put("name", productStats.getSpu_name());
            row.put("amount", productStats.getOrder_amount());
            row.put("ct", productStats.getOrder_ct());
            rowList.add(row);
        }

        dataMap.put("columns", columnList);
        dataMap.put("rows", rowList);

        resMap.put("status", 0);
        resMap.put("data", dataMap);

        return resMap;
    }

//    @RequestMapping("/province")
//    public Map getProvinceStats(@RequestParam(value = "date", defaultValue = "0") Integer date) {
//        if (date == 0) {
//            date = now();
//        }
//
//        List<ProvinceStats> provinceStatsList = provinceStatsService.getProvinceStats(date);
//
//        Map resMap = new HashMap();
//
//        Map dataMap = new HashMap();
//
//        List mapList = new ArrayList();
//        for (ProvinceStats provinceStats : provinceStatsList) {
//            Map map = new HashMap();
//            map.put("name", provinceStats.getProvince_name());
//            map.put("value", provinceStats.getOrder_amount());
//            mapList.add(map);
//        }
//
//        dataMap.put("mapData", mapList);
//        dataMap.put("valueName", "交易额");
//
//        resMap.put("status", 0);
//        resMap.put("data", dataMap);
//
//        return resMap;
//
//    }

    @RequestMapping("/visitor")
    public Object getVisitorStats(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStats(date);
        VisitorStats newVisitorStats = new VisitorStats();
        VisitorStats oldVisitorStats = new VisitorStats();
        for (VisitorStats visitorStats : visitorStatsList) {
            //if(visitorStats.getIs_new().equals("1")){
            if ("1".equals(visitorStats.getIs_new())) {
                //新访客
                newVisitorStats = visitorStats;
            } else {
                //老访客
                oldVisitorStats = visitorStats;
            }
        }

        String json = "{\"status\": 0,\"data\": " +
                "{\"columns\": [" +
                "{\"name\": \"类别\",\"id\": \"type\"}," +
                "{\"name\": \"新用户\",\"id\": \"new\"}," +
                "{\"name\": \"老用户\",\"id\": \"old\"}]," +
                "\"rows\": [" +
                "{\"type\": \"用户数(人)\",\"new\": " + newVisitorStats.getUv_ct() + ",\"old\": " + oldVisitorStats.getUv_ct() + "}," +
                "{\"type\": \"总访问页面(次)\",\"new\": " + newVisitorStats.getPv_ct() + ",\"old\": " + oldVisitorStats.getPv_ct() + "}," +
                "{\"type\": \"跳出率(%)\",\"new\": " + newVisitorStats.getUjRate() + ",\"old\": " + oldVisitorStats.getUjRate() + "}," +
                "{\"type\": \"平均在线时长(秒)\",\"new\": " + newVisitorStats.getDurPerSv() + ",\"old\": " + oldVisitorStats.getDurPerSv() + "}," +
                "{\"type\": \"平均访问页面数(次)\",\"new\": " + newVisitorStats.getPvPerSv() + ",\"old\": " + oldVisitorStats.getPvPerSv() + "}]}}";

        return json;
    }

    @RequestMapping("/keyword")
    public String getKeywordStats(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        if (date == 0) {
            date = now();
        }
        List<KeywordStats> keywordStatsList = keywordStatsService.getkeywordStats(date, limit);
        StringBuilder json = new StringBuilder("{\"status\": 0,\"data\": [");
        for (int i = 0; i < keywordStatsList.size(); i++) {
            KeywordStats keywordStats = keywordStatsList.get(i);
            json.append("{\"name\": \"" + keywordStats.getKeyword() + "\",\"value\": " + keywordStats.getCt() + "}");
            if(i < keywordStatsList.size() - 1){
                json.append(",");
            }
        }
        json.append("]}");

        return json.toString();
    }

    @RequestMapping("/hr")
    public String getVisitorStatsByHr(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        //从service中获取分时访问情况
        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStatsByHr(date);
        //定义一个数组 ，用于存放24小时的分时统计情况
        VisitorStats[] visitorStatsArr = new VisitorStats[24];
        //从集合中获取结果，赋值给数组中对应的小时
        for (VisitorStats visitorStats : visitorStatsList) {
            visitorStatsArr[visitorStats.getHr()] = visitorStats;
        }

        //用于存放24小时的集合
        List hrList = new ArrayList();
        //用于存放每个小时uv情况的集合
        List uvList = new ArrayList();
        //用于存放每个小时pv情况的集合
        List pvList = new ArrayList();
        //用于存放新访客每个小时uv情况的集合
        List newUvList = new ArrayList();

        //从数组中获取一天24的数据
        for (int hr = 0; hr < visitorStatsArr.length; hr++) {
            VisitorStats visitorStats = visitorStatsArr[hr];
            if (visitorStats != null) {
                uvList.add(visitorStats.getUv_ct());
                pvList.add(visitorStats.getPv_ct());
                newUvList.add(visitorStats.getNew_uv());
            } else {
                uvList.add(0L);
                pvList.add(0L);
                newUvList.add(0L);
            }
            hrList.add(String.format("%02d", hr));
        }

        String json = "{\"status\": 0,\"data\": {\"categories\": " +
                "[\"" + StringUtils.join(hrList, "\",\"") + "\"]," +
                "\"series\": [" +
                "  {\"name\": \"UV\",\"data\": [" + StringUtils.join(uvList, ",") + "]}," +
                "  {\"name\": \"PV\",\"data\": [" + StringUtils.join(pvList, ",") + "]}," +
                "  {\"name\": \"newUV\",\"data\": [" + StringUtils.join(newUvList, ",") + "]}" +
                "]}}";

        return json;



    }

    //方式2：封装对象，通过将对象转换的json格式字符串的方式 返回json数据
    @RequestMapping("/orderbyyear")
    public Map getOrderByYear() {

        //调用service获取品类交易额排行
        List<ProtalStats> totalamountByYea = protalPersonService.getTotalamountByYea();
        Map resMap = new HashMap();
        resMap.put("status", 0);
        List dataList = new ArrayList();
        for (ProtalStats productStats : totalamountByYea) {
            Map dataMap = new HashMap();
            dataMap.put("name", productStats.getYearbasename());
            dataMap.put("value", productStats.getTotal_amount());
            dataList.add(dataMap);
        }

        resMap.put("data", dataList);
        return resMap;
    }

    // 0  代表 按照小时
    // 1  代表 按照分钟
    @RequestMapping("/type")
    public Map getProvinceStats(@RequestParam(value = "type", defaultValue = "0") Integer type) {
        Map resMap = new HashMap();
        if(type == 0){
            List<TimeData> visitorByH = visitorStatsService.getVisitorByH();
            resMap.put("status", 0);
            List mapList = new ArrayList();
            Map dataMap = new HashMap();
            for (TimeData timeData : visitorByH) {
                dataMap.put(timeData.getTime(),timeData.getUv());
                resMap.put("data", dataMap);
            }
            mapList.add(dataMap);
        }
        return resMap;

    }
































    @RequestMapping("/sugar/api/getGmvByTm1")
    public JsonRootBean getGmvByTm1(@RequestParam(value = "date", defaultValue = "0") Integer date, @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
        if (date == 0) {
            date = now();
        }
        List<ProductStats> productStats = productStatsService.getGMVByTm(date, limit);
        List<String> tms = new ArrayList<>();// 匹配品牌
        List<BigDecimal> series = new ArrayList<>();// 销售额
        List<Series>series1 = new ArrayList<>();// 装Series对象
        Series s = new Series();// 创建一个对象
        s.setName("品牌");// 设置名字
        for (ProductStats productStat : productStats) {
            tms.add(productStat.getTm_name());
            series.add(productStat.getOrder_amount());
        }

        s.setData(series);


        JsonRootBean rootBean = new JsonRootBean();
        rootBean.setMsg("");
        rootBean.setStatus(0);


        series1.add(s);
        Data data = new Data();
        data.setSeries(series1);
        data.setCategories(tms);

        rootBean.setData(data);
        return rootBean;
    }


    private Integer now() {
        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
        return Integer.valueOf(yyyyMMdd);
    }
}
